<template>
    <v-container class="mt-4">
         <v-container>
            <h4 class="mb-3">菜单管理</h4>
        </v-container>

        <v-row class="mb-2">
            <v-col :md="6" :lg="4" :xl="3" :sm="10">
                 <AutocompleteOrg v-model="org"></AutocompleteOrg>
            </v-col>
            <v-col cols="2" class="d-flex align-center">
                 <v-btn  depressed  color="primary" @click="saveMenu" :loading="saving">保存</v-btn>
            </v-col>
        </v-row>
        <v-treeview
            selectable
            item-key="id"
            item-text="title"
            :items="menus"
            selection-type="independent"
            v-model="selectedMenu"
            open-on-click
            activatable
        >
            <template v-slot:prepend="{ item }">
                <v-icon>{{ item.icon ? item.icon : "mdi-folder"}}</v-icon>
            </template>
        </v-treeview>
    </v-container>
</template>

<script>
    import axios from "axios";
    import AutocompleteOrg from "../../widgets/AutocompleteOrg.vue";

    export default {
    data: () => ({
        org: null,
        menus: [],
        selectedMenu: [],
        search: null,
        saving: false,
    }),

    components: {
        AutocompleteOrg: AutocompleteOrg,
    },

    watch: {
        org (val) {
            axios.get(`/menus/org/${val.id}`).then((response) => {
                this.selectedMenu = response.data.data;
            })
            .catch(function () {})
            .then(function () {});
        }
    },

    created() {
        this.loadMenu();
        this.search='';
    },

    methods: {
            loadMenu() {
                axios.get(`/menus/tree`).then((response) => {
                    this.menus = response.data.data.menu;
                })
                .catch(function () {})
                .then(function () {});
            },

            saveMenu() {
                if(!this.org.id) {
                    return;
                };

                const that = this;
                that.saving = true;
                axios.post(`/menus/org/${this.org.id}`, {ids: this.selectedMenu}).then((response) => {
                    if (response.data.code == 0) {
                        this.$toast.open({
                            message: response.data.msg,
                            type: 'success',
                            position: 'top-right',
                        });
                    } else {
                        this.$toast.open({
                            message: response.data.msg,
                            type: 'error',
                            position: 'top-right',
                        });
                    }
                })
                .catch(function () {})
                .then(function () {
                     that.saving = false;
                });
            }
        },
    };
</script>
